//
//  WhsInListViewController.m
//  HAODE
//
//  Created by panquanReabam.com on 15/9/26.
//  Copyright (c) 2015年 reabam.com. All rights reserved.
//

#import "WhsInListViewController.h"
#import "WhsOutAddWhsInDetailViewController.h"
#import "MJRefresh.h"
#import "ToResiduePayViewController.h"
#import "TheLoginViewController.h"
#import "PlaceOrderViewController.h"
#import "WhsInListModel.h"
#import "CommonListCell.h"
#import "FilterView.h"
@interface WhsInListViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UISearchBarDelegate,ToResiduePayViewControllerDelegate,FilterViewDelegate>
@property (strong, nonatomic) NSString*sats;
@end
@implementation WhsInListViewController
{
    MJRefreshHeaderView* _header;
    MJRefreshFooterView* _footer;
    BOOL saveAccount;
    int pageNumber;
    UIButton*sat;
    UIButton*sat1;
    UIButton*sat2;
    NSMutableArray*ModelArray;
    NSMutableArray*searchBeans;
    NSMutableArray*DataLine;
    NSString* TotalCount;
    UITableView *table;
    UIButton*btnNormal;
    UIButton*screeningBtn;
    UIButton*screeningImage;
    MBProgressHUD *progressHud;
    NSMutableArray*mItemsArray;
    UIView*tableHeaderView;
}
@synthesize alt = alt;
-(void)BackAction:(UIButton *)sender{
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    self.title=@"入库";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
        UIButton*addBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 0.0,  60/2, 60/2)];
        [addBtn setImage:[UIImage imageNamed:@"tianjia"] forState:UIControlStateNormal];
        [addBtn addTarget:self action:@selector(addProduct:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem* myBtnBtn = [[UIBarButtonItem alloc] initWithCustomView:addBtn];
        self.navigationItem.rightBarButtonItem = myBtnBtn;
    
    
}
-(void)addProduct:(UIButton*)sender{
    PlaceOrderViewController *placeOrderVC=[[PlaceOrderViewController alloc] init];
    placeOrderVC.ptype=@"saleItem";
    placeOrderVC.Whs=@"WhsIn";
    [self.navigationController pushViewController:placeOrderVC animated:YES];
}

-(void)secondViewController:(ToResiduePayViewController *)secondViewController upster:(NSString *)upsterData chooseState:(NSString *)chooseStates{
    [self AddData];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.sats=@"newOrder";
    _orderSort=@"desc";
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    table.delegate=self;
    table.dataSource=self;
    [table registerClass:[CommonListCell class] forCellReuseIdentifier:@"WhsInListViewController"];
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview: table];
    [self AddData];
    
}
-(void)AddData{
    
    [self tableHeaderView];
    [self requestData];
    [self addFooter];
    [self addheader];
}
-(void)requestData{
    ModelArray=[[NSMutableArray alloc]init];
    pageNumber = 1;
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"1" forKey:@"pageIndex"];
    [param setValue:@"20" forKey:@"pageSize"];
    [param setValue:_orderSort forKey:@"whsInSort"];
    [param setValue:self.sats forKey:@"whsInField"];
    [param setValue:searchBeans forKey:@"searchBeans"];
    [HttpRequest requestData:@"Business/WhsIn/List" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                if (searchBeans.count>0) {
                    UIImage *img=[UIImage imageNamed:@"shaixuan_hight"];
                    UIImage *tinted = [img rt_tintedImageWithColor:luseColor];
                    [screeningBtn setTitleColor:luseColor forState:UIControlStateNormal];
                    [screeningImage setImage:tinted forState:UIControlStateNormal];
                    
                }else{
                    [screeningBtn setTitleColor:shenhuiColor forState:UIControlStateNormal];
                    [screeningImage setImage:[UIImage imageNamed:@"shaixuan"] forState:UIControlStateNormal];
                }
                
                mItemsArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                for (NSDictionary *dic in mItemsArray) {
                    WhsInListModel *dataModel=[WhsInListModel dataModelWithWhsInListDict:dic];
                    [ModelArray addObject:dataModel];
                    
                }
                
                [table reloadData];
            }else{
                [Global hideProgressHUDInternal:self.view];
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    TheLoginViewController *detailViewController = [[TheLoginViewController alloc] init];
                    [self.navigationController pushViewController:detailViewController animated:YES];
                }
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
    
}

//下拉刷新
- (void)addheader
{
    MJRefreshHeaderView* footer = [MJRefreshHeaderView header];
    footer.scrollView = table;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        searchBeans=nil;
        self.sats=@"newOrder";
        [self requestData];
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:3.0f];
        NSLog(@"%@--->正在刷新", refreshView.class);
    };
}
//上拉刷新
- (void)addFooter
{
    MJRefreshFooterView* footer = [MJRefreshFooterView footer];
    footer.scrollView = table;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        
        NSLog(@"---------%d",pageNumber);
        NSLog(@"++++%d",TotalCount.intValue/5);
        if (TotalCount.intValue/20>=pageNumber) {
            pageNumber++;
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            NSString* Token = [user objectForKey:@"tokenId"];
            if (Token ==nil) {
                Token=@"dd";
            }
            NSMutableDictionary *param = [NSMutableDictionary new];
            [param setValue:Token forKey:@"tokenId"];
            [param setValue:[NSString stringWithFormat:@"%d" ,pageNumber] forKey:@"pageIndex"];
            [param setValue:@"20" forKey:@"pageSize"];
            [param setValue:_orderSort forKey:@"whsInSort"];
            [param setValue:self.sats forKey:@"whsInField"];
            [param setValue:searchBeans forKey:@"searchBeans"];
            [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
            [HttpRequest requestData:@"Business/WhsIn/List" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        mItemsArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                        for (NSDictionary *dic in mItemsArray) {
                            WhsInListModel *dataModel=[WhsInListModel dataModelWithWhsInListDict:dic];
                            [ModelArray addObject:dataModel];
                        }
                        [table reloadData];
                    }else{
                        [Global hideProgressHUDInternal:self.view];
                        if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                            TheLoginViewController *detailViewController = [[TheLoginViewController alloc] init];
                            [self.navigationController pushViewController:detailViewController animated:YES];
                        }}}
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    [Global showTextHudSub:@"连接失败" view:self.view];
                }
                
            }];
            
            
        }else{
            
            NSString *requestResultStr=@"没有更多数据了！";
            [Global showTextHudSub:requestResultStr view:self.view];
            
        }
        
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:3.0f];
        NSLog(@"%@--->正在刷新", refreshView.class);
    };
}
- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    [table reloadData];
    [refreshView endRefreshing];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [ModelArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommonListCell*cell = [tableView dequeueReusableCellWithIdentifier:@"WhsInListViewController"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.WhsInListModel=ModelArray[indexPath.row];
    return cell;
    
    
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    return  108;
    
}

#pragma mark - Table view delegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   
        WhsInListModel *ScreeningModel=ModelArray[indexPath.row];
        WhsOutAddWhsInDetailViewController *detailViewController = [[WhsOutAddWhsInDetailViewController alloc] init];
        detailViewController.orderId=ScreeningModel.whsInId;
        detailViewController.titleName=@"入库详情";
        detailViewController.Whs=@"WhsIn";
        [self.navigationController pushViewController:detailViewController animated:YES];

}
-(void)sxuan:(UIButton*)sender{
    FilterView *filterView=[FilterView FilterViewWithSize:CGSizeMake(ScreenWidth, ScreenHeight)];
    filterView.typeStr=@"whsIn";
    filterView.delegate=self;
    filterView.selectedSearchBeansArray=searchBeans;
    [filterView show];
    
}
#pragma mark FilterViewDelegate
-(void)confirmFilter:(NSMutableArray *)searchBeansArray
{
    searchBeans=searchBeansArray;
    [self requestData];
}


- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
-(void)tableHeaderView{
    
    
    tableHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth,80/2)];
    tableHeaderView.backgroundColor= zuiqianhuiColor;
    table.tableHeaderView=tableHeaderView;
    sat=[[UIButton alloc]initWithFrame:CGRectMake(18, 0, ScreenWidth/3, 40)];
    [sat setTitle:@"最新" forState:UIControlStateNormal];
    [sat setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    sat.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
    sat.titleLabel.font=[UIFont systemFontOfSize:14];
    [sat addTarget:self action:@selector(sat:) forControlEvents:UIControlEventTouchUpInside];
    [tableHeaderView addSubview:sat];
    
    sat1=[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth/3-7, 0, ScreenWidth/3, 40)];
    [sat1 setTitle:@"金额     " forState:UIControlStateNormal];
    [sat1 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    sat1.titleLabel.font=[UIFont systemFontOfSize:14];
    [sat1 addTarget:self action:@selector(sat1:) forControlEvents:UIControlEventTouchUpInside];
    sat1.titleLabel.textAlignment=NSTextAlignmentCenter;
    [tableHeaderView addSubview:sat1];
    btnNormal=[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth/2+10, 15, 10, 10)];
    [btnNormal setImage:[UIImage imageNamed:@"jiantou_normal"] forState:UIControlStateNormal];
    [btnNormal addTarget:self action:@selector(sat1:) forControlEvents:UIControlEventTouchUpInside];
    [tableHeaderView addSubview:btnNormal];
    screeningBtn=[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-78,  0, 60,40)];
    [screeningBtn.layer setCornerRadius:2.0];
    [screeningBtn.layer setBorderWidth:0];
    [screeningBtn.layer setMasksToBounds:YES];
    [screeningBtn addTarget:self action:@selector(sxuan:) forControlEvents:UIControlEventTouchUpInside];
    CGColorSpaceRef colorSpace2 = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref2 = CGColorCreate(colorSpace2,(CGFloat[]){153/255.0,153/255.0, 153/255.0, 1.0   });
    [screeningBtn.layer setBorderColor:colorref2];//边框颜色
    [screeningBtn setTitle:@"筛选" forState:UIControlStateNormal];
    screeningBtn.titleLabel.font=[UIFont systemFontOfSize:14];
    [screeningBtn setTitleColor:shenhuiColor forState:UIControlStateNormal];
    screeningBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentRight;
    [tableHeaderView addSubview:screeningBtn];
    screeningImage = [[UIButton alloc] initWithFrame:CGRectMake(3.5,5, 30, 30)];
    [screeningImage setImage:[UIImage imageNamed:@"shaixuan"] forState:UIControlStateNormal];
    [screeningImage addTarget:self action:@selector(sxuan:) forControlEvents:UIControlEventTouchUpInside];
    [screeningBtn addSubview:screeningImage];
    //    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    //    NSString* Token = [user objectForKey:@"tokenId"];
    //    if (Token ==nil) {
    //        Token=@"dd";
    //    }
    //    NSMutableDictionary *param = [NSMutableDictionary new];
    //    [param setValue:Token forKey:@"tokenId"];
    //    [param setValue:@"order" forKey:@"filterType"];
    //    [HttpRequest requestData:@"Common/AdvancedFilterList" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
    //        if (isSuccess) {
    //            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
    //                [Global hideProgressHUDInternal:self.view];
    //
    //                NSMutableArray * mItemsArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
    //                for (NSDictionary *dic in mItemsArray) {
    //                    OrderModel *dataModel=[OrderModel ScreeningDataModelWithDict:dic];
    //                    [ScreeningModelArray addObject:dataModel];
    //
    //                }
    //            }else{
    //            }
    //
    //        }
    //        else
    //        {
    //            [Global hideProgressHUDInternal:self.view];
    //
    //            [Global showTextHudSub:@"连接失败" view:self.view];
    //        }
    //
    //    }];
}
-(void)sat:(UIButton*)sender{
    [sat1 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [sat setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    searchBeans=nil;
    self.sats=@"newOrder";
    [self requestData];
}
-(void)sat1:(UIButton*)sender{
    saveAccount=!saveAccount;
    if (saveAccount) {
        self.sats=@"amount";
        _orderSort=@"desc";
        [self requestData];
        [sat setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [sat1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btnNormal setImage:[UIImage imageNamed:@"shang_hight"] forState:UIControlStateNormal];
    }else{
        
        self.sats=@"amount";
        _orderSort=@"asc";
        [self requestData];
        [sat setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [sat1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btnNormal setImage:[UIImage imageNamed:@"xia_hight"] forState:UIControlStateNormal];
        
    }
}

@end

